package com.atguigu.filter;

import com.atguigu.utils.JdbcUtils;

import javax.servlet.*;
import java.io.IOException;

/**
 * 给所有的调用Service方法加上try-catch的过滤器
 */
public class TransactionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        try {
            filterChain.doFilter(servletRequest, servletResponse);
            JdbcUtils.commitAndClose();//提交事物
        } catch (Exception e) {
            JdbcUtils.rollbackAndClose();//回滚事物
            e.printStackTrace();
            throw new RuntimeException(e);//将异常抛给Tomcat服务器管理展示友好的错误页面
        }
    }

    @Override
    public void destroy() {

    }
}
